// 文章模块
const path = require('path');
const db = require(path.join(__dirname, '../common/db.js'));
const express = require('express');
const router = express.Router();

// 获取文章分类列表
router.get('/article/cates', async (res, req) => {
    let sql = 'select id, name, alias, is_delete from cates';
    let ret = await db.db(sql, []);
    req.json({
        status: 0,
        message: '获取文章分类列表成功',
        data: ret
    })
})

// 新增文章分类
router.post('/article/addcates', async (res, req) => {
    let params = res.body;
    let sql = 'insert into cates set ?';
    let ret = await db.db(sql, {
        name: params.name,
        alias: params.alias
    });
    if (ret.affectedRows > 0) { // 插入成功
        req.json({
            status: 0,
            message: '新增文章分类成功'
        })
    } else {
        req.json({
            status: 1,
            message: '新增文章分类失败'
        })
    }
})

// 根据 Id 删除文章分类
router.get('/article/deletecate/:id', async (res, req) => {
    let params = res.params;
    // let sql = 'delete from cates where id = ?';
    let sql = 'update cates set is_delete = 1 where id = ?';
    let ret = await db.db(sql, params.id);
    if (ret.affectedRows > 0) {
        req.json({
            status: 0,
            message: '删除文章分类成功'
        })
    } else {
        req.json({
            status: 1,
            message: '删除文章分类失败'
        })
    }
})

// 根据 Id 获取文章分类数据
router.get('/article/cates/:id', async (res, req) => {
    let params = res.params;
    let sql = 'select id, name, alias, is_delete from cates where id = ?';
    let ret = await db.db(sql, params.id);
    if (ret.length > 0) {
        req.json({
            status: 0,
            message: '获取文章分类数据成功',
            data: ret
        })
    } else {
        req.json({
            status: 0,
            message: '获取文章分类数据失败'
        })
    }
})

// 根据 Id 更新文章分类数据
router.post('/article/updatecate', async (res, req) => {
    let params = res.body;
    let sql = 'update cates set ? where id = ?';
    let ret = await db.db(sql, [
        {
            name: params.name,
            alias: params.alias
        },
        params.id
    ])
    if (ret.affectedRows > 0) {
        req.json({
            status: 0,
            message: '更新文章分类成功'
        })
    } else {
        req.json({
            status: 1,
            message: '更新文章分类失败'
        })
    }
})

module.exports = router;